package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    IPaymentInfoService paymentInfoService;

    @Autowired
    RemoteOrderInfoService remoteOrderInfoService;

    /**
     * 提交支付宝支付请求
     *
     * @param orderNo 订单编号
     * @return 支付宝支付页面的HTML内容
     */
    @SneakyThrows
    @Override
    public String submitAlipay(String orderNo) {
        // 保存支付信息
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);

        R<OrderInfo> orderInfoR = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if(R.FAIL==orderInfoR.getCode()){
            throw new ServiceException(orderInfoR.getMsg());
        }
        OrderInfo orderInfo = orderInfoR.getData();
        // 创建支付宝手机网站支付请求
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);

        // 构建支付业务参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        map.put("total_amount", paymentInfo.getAmount());
//        map.put("total_amount", "0.01");
        map.put("subject", paymentInfo.getContent());

        Date orderCreateTime = orderInfo.getCreateTime();
        LocalDateTime orderCreateDateTime;
        if(orderCreateTime!=null){
            orderCreateDateTime = orderCreateTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        }else  {
            orderCreateDateTime = LocalDateTime.now();
        }
        LocalDateTime expireTime = orderCreateDateTime.plusMinutes(30);
        String expireTimeStr = expireTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        map.put("time_expire",expireTimeStr);
        alipayRequest.setBizContent(JSON.toJSONString(map));

        // 执行支付请求并返回支付页面内容
        return alipayClient.pageExecute(alipayRequest).getBody();
    }


}
